<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>

  <body>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
    <script>
      /*
            需求：
                1. 先让用户登录
                2. 验证用户是否已经登录
                3. 点赞
                顺次执行
        */

      // 1 . 封装一个 能返回 Promise 实例的 方法
      function PromiseAjax(opts = {}) {
        let p = new Promise((resolve, reject) => {
          $.ajax({
            // url, type, data
            ...opts,
            success(res) {
              resolve(res)
            },
            error(err) {
              reject(err)
            }
          })
        })
        return p
      }

      // 2, 声明一个async 函数
      async function req() {
        // 3. 先登录
        let res1 = await PromiseAjax({
          url: 'http://kumanxuan1.f3322.net:8809/users/login',
          type: 'post',
          data: {
            username: '13700000000',
            password: '1111'
          }
        })
        // console.log(res1);
        let {
          token
        } = res1.data
        // 4. 拿token到服务器去验证
        let res2 = await PromiseAjax({
          url: 'http://kumanxuan1.f3322.net:8809/users/currentUser',
          headers: {
            'x-authorization': token
          }
        })
        // console.log(res2);
        // 5. 点赞
        let res3 = await PromiseAjax({
          url: 'http://kumanxuan1.f3322.net:8809/strategies/strategyThumbup',
          headers: {
            'x-authorization': token
          },
          data: {
            sid: '5e33bd2a9c300000e9003ae3'
          },
          type: 'post'
        })
        console.log(res3);
      }

      req()
    </script>
  </body>

</html>